/**
 * 文件上传相关API
 */

import { http } from "@/utils/http";

// 文件上传响应类型
export interface FileUploadResult {
  fileName: string;
  originalFileName: string;
  fileSize: number;
  contentType: string;
  relativePath: string;
  fileUrl: string;
  uploadTime: number;
}

// 通用响应类型
export interface OperationResult {
  code: number;
  message: string;
  data?: any;
  timestamp: number;
}

// 文件上传结果响应类型
export interface FileUploadResponse {
  code: number;
  message: string;
  data: FileUploadResult;
  timestamp: number;
}

// 头像URL响应类型
export interface AvatarUrlResponse {
  code: number;
  message: string;
  data: string;
  timestamp: number;
}

// 文件验证响应类型
export interface FileValidationResponse {
  code: number;
  message: string;
  data: boolean;
  timestamp: number;
}

/**
 * 上传当前用户头像
 * @param file 头像文件
 * @returns Promise<FileUploadResponse>
 */
export const uploadMyAvatarApi = (file: File): Promise<FileUploadResponse> => {
  console.log(`API调用: uploadMyAvatarApi`, file);

  const formData = new FormData();
  formData.append("file", file);

  return http.request<FileUploadResponse>("post", "/api/user/uploadAvatar", {
    data: formData
  });
};

/**
 * 删除当前用户头像
 * @returns Promise<OperationResult>
 */
export const deleteMyAvatarApi = (): Promise<OperationResult> => {
  console.log(`API调用: deleteMyAvatarApi`);

  return http.request<OperationResult>("delete", "/api/user/deleteAvatar");
};

/**
 * 获取当前用户头像URL
 * @returns Promise<AvatarUrlResponse>
 */
export const getMyAvatarApi = (): Promise<AvatarUrlResponse> => {
  console.log(`API调用: getMyAvatarApi`);
  return http.request<AvatarUrlResponse>("get", "/api/user/getAvatar");
};

/**
 * 管理员为指定用户上传头像
 * @param userId 用户ID
 * @param file 头像文件
 * @returns Promise<FileUploadResponse>
 */
export const uploadUserAvatarApi = (
  userId: number,
  file: File
): Promise<FileUploadResponse> => {
  console.log(`API调用: uploadUserAvatarApi(${userId})`, file);

  if (!userId || userId <= 0) {
    console.error("无效的用户ID:", userId);
    return Promise.reject(new Error("用户ID不能为空"));
  }

  const formData = new FormData();
  formData.append("file", file);

  return http.request<FileUploadResponse>(
    "post",
    `/admin/users/${userId}/uploadAvatar`,
    {
      data: formData
    }
  );
};

/**
 * 管理员删除指定用户头像
 * @param userId 用户ID
 * @returns Promise<OperationResult>
 */
export const deleteUserAvatarApi = (
  userId: number
): Promise<OperationResult> => {
  console.log(`API调用: deleteUserAvatarApi(${userId})`);

  if (!userId || userId <= 0) {
    console.error("无效的用户ID:", userId);
    return Promise.reject(new Error("用户ID不能为空"));
  }

  return http.request<OperationResult>(
    "delete",
    `/admin/users/${userId}/deleteAvatar`
  );
};

/**
 * 删除文件（管理员）
 * @param relativePath 文件相对路径
 * @returns Promise<OperationResult>
 */
export const deleteFileApi = (
  relativePath: string
): Promise<OperationResult> => {
  console.log(`API调用: deleteFileApi(${relativePath})`);

  if (!relativePath) {
    console.error("文件路径不能为空:", relativePath);
    return Promise.reject(new Error("文件路径不能为空"));
  }

  return http.request<OperationResult>("delete", "/api/upload/deleteFile", {
    params: { relativePath }
  });
};

/**
 * 验证图片文件
 * @param file 要验证的文件
 * @returns Promise<FileValidationResponse>
 */
export const validateImageFileApi = (
  file: File
): Promise<FileValidationResponse> => {
  console.log(`API调用: validateImageFileApi`, file);

  const formData = new FormData();
  formData.append("file", file);

  return http.request<FileValidationResponse>(
    "post",
    "/api/upload/validateImage",
    {
      data: formData
    }
  );
};

/**
 * 文件上传工具函数
 */
export class FileUploadUtils {
  // 支持的图片格式
  static readonly SUPPORTED_IMAGE_TYPES = [
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/gif",
    "image/webp"
  ];

  // 最大文件大小（5MB）
  static readonly MAX_FILE_SIZE = 5 * 1024 * 1024;

  /**
   * 检查文件类型是否支持
   * @param file 文件对象
   * @returns boolean
   */
  static isImageTypeSupported(file: File): boolean {
    return this.SUPPORTED_IMAGE_TYPES.includes(file.type);
  }

  /**
   * 检查文件大小是否符合要求
   * @param file 文件对象
   * @returns boolean
   */
  static isFileSizeValid(file: File): boolean {
    return file.size <= this.MAX_FILE_SIZE;
  }

  /**
   * 格式化文件大小
   * @param bytes 字节数
   * @returns string
   */
  static formatFileSize(bytes: number): string {
    if (bytes === 0) return "0 Bytes";

    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  }

  /**
   * 获取文件扩展名
   * @param fileName 文件名
   * @returns string
   */
  static getFileExtension(fileName: string): string {
    return fileName.slice(((fileName.lastIndexOf(".") - 1) >>> 0) + 2);
  }

  /**
   * 验证文件是否为有效图片
   * @param file 文件对象
   * @returns Promise<boolean>
   */
  static async validateImageFile(file: File): Promise<boolean> {
    // 进行基本验证
    if (!this.isImageTypeSupported(file)) {
      throw new Error(`不支持的文件类型。支持的格式：JPG、PNG、GIF、WebP`);
    }

    if (!this.isFileSizeValid(file)) {
      throw new Error(
        `文件大小超过限制。最大允许：${this.formatFileSize(this.MAX_FILE_SIZE)}`
      );
    }

    // 客户端验证通过
    return true;
  }

  /**
   * 创建图片预览URL
   * @param file 文件对象
   * @returns string
   */
  static createImagePreviewUrl(file: File): string {
    return URL.createObjectURL(file);
  }

  /**
   * 释放图片预览URL
   * @param url 预览URL
   */
  static revokeImagePreviewUrl(url: string): void {
    URL.revokeObjectURL(url);
  }
}
